package com.lp.serialportlp

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import java.io.BufferedWriter
import java.io.File
import java.io.FileNotFoundException
import java.io.FileWriter
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date

@SuppressLint("StaticFieldLeak")
object MyLog {


  private var dirsFile: File? = null

  @SuppressLint("StaticFieldLeak")
   var MYLOG_SWITCH = true // 是否打印日志

  @SuppressLint("StaticFieldLeak")
   var MYLOG_WRITE_TO_FILE = true // 是否将日志写入文件开关

  @SuppressLint("StaticFieldLeak")
  private const val MYLOG_TYPE = 'v' // 输入日志类型，w代表只输出告警信息等，v代表输出所有信息

  @SuppressLint("StaticFieldLeak")
  var MYLOG_PATH_SDCARD_DIR =
    Environment.getExternalStorageDirectory().toString() + File.separator + "Android" +
      File.separator + "data" + File.separator + "Logcat" + File.separator + "Log" // 日志文件在sdcard中的路径
  private const val SDCARD_LOG_FILE_SAVE_DAYS = 15 // sd卡中日志文件的最多保存天数

  @SuppressLint("StaticFieldLeak")
  private const val MYLOGFILEName = "Log.txt" // 本类输出的日志文件名称

  @SuppressLint("StaticFieldLeak")
  private val myLogSdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") // 日志的输出格式

  @SuppressLint("StaticFieldLeak")
  private val logfile = SimpleDateFormat("yyyy-MM-dd") // 日志文件格式

  @SuppressLint("StaticFieldLeak")
  var mContext: Context? = null

  @JvmStatic
  fun setContext(context: Context?) {
    mContext = context
  }


  fun w(tag: String, msg: Any) { // 警告信息
    log(tag, msg.toString(), 'w')
  }

  fun e(tag: String, msg: Any) { // 错误信息
    log(tag, msg.toString(), 'e')
  }

  fun d(tag: String, msg: Any) { // 调试信息
    log(tag, msg.toString(), 'd')
  }


  fun i(tag: String, msg: Any) { //
    log(tag, msg.toString(), 'i')
  }


  fun v(tag: String, msg: Any) {
    log(tag, msg.toString(), 'v')
  }


  fun w(tag: String, text: String) {
    log(tag, text, 'w')
  }


  fun e(tag: String, text: String) {
    log(tag, text, 'e')
  }


  fun d(tag: String, text: String) {
    log(tag, text, 'd')
  }


  fun i(tag: String, text: String) {
    log(tag, text, 'i')
  }


  fun v(tag: String, text: String) {
    log(tag, text, 'v')
  }

  /**
   * 根据tag, msg和等级，输出日志
   * @param tag
   * @param msg
   * @param level
   */
  private fun log(tag: String, msg: String, level: Char) {
    var msg = msg
    if (MYLOG_SWITCH) { //日志文件总开关

      if (TextUtils.isEmpty(msg)) {
        return
      }


      if ('e' == level && ('e' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { // 输出错误信息
        Log.e(tag, msg)
      } else if ('w' == level && ('w' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {
        Log.w(tag, msg)
      } else if ('d' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {
        Log.d(tag, msg)
      } else if ('i' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {
        Log.i(tag, msg)
      } else {
        Log.v(tag, msg)
      }
      if (MYLOG_WRITE_TO_FILE)  //日志写入文件开关
        writeLogtoFile(level.toString(), tag, msg)
    }
  }

  /**
   * 打开日志文件并写入日志
   * @param mylogtype
   * @param tag
   * @param text
   */
  private fun writeLogtoFile(mylogtype: String, tag: String, text: String) { // 新建或打开日志文件
    val nowtime = Date()
    val needWriteFiel = logfile.format(nowtime)
    val needWriteMessage =
      myLogSdf.format(nowtime) + "    " + mylogtype + "    " + tag + "    " + text

    if (Build.VERSION.SDK_INT >= 30) {
      MYLOG_PATH_SDCARD_DIR = mContext!!.externalCacheDir.toString() + File.separator + "Log"
    }

    dirsFile = File(MYLOG_PATH_SDCARD_DIR)
    if (!dirsFile!!.exists()) {
      dirsFile!!.mkdirs()
    }
    //Log.i("创建文件","创建文件");
    val file = File(dirsFile.toString(), needWriteFiel + MYLOGFILEName) // MYLOG_PATH_SDCARD_DIR
    if (!file.exists()) {
      try {
        //在指定的文件夹中创建文件
        file.createNewFile()
      } catch (e: Exception) {
      }
    }

    try {
      val filerWriter = FileWriter(file, true) // 后面这个参数代表是不是要接上文件中原来的数据，不进行覆盖
      val bufWriter = BufferedWriter(filerWriter)
      bufWriter.write(needWriteMessage)
      bufWriter.newLine()
      bufWriter.close()
      filerWriter.close()
    } catch (e: FileNotFoundException) {
    } catch (e: IOException) {
      e.printStackTrace()
    }
  }

  /**
   * 删除制定的日志文件
   */
  fun delFile() { // 删除日志文件
    val needDelFiel = logfile.format(dateBefore)
    val dirPath = Environment.getExternalStorageDirectory()
    val file = File(dirPath, needDelFiel + MYLOGFILEName) // MYLOG_PATH_SDCARD_DIR
    if (file.exists()) {
      file.delete()
    }
  }


  val dateBefore: Date
    /**
     * 得到现在时间前的几天日期，用来得到需要删除的日志文件名
     */
    get() {
      val nowtime = Date()
      val now = Calendar.getInstance()
      now.time = nowtime
      now[Calendar.DATE] = now[Calendar.DATE] - SDCARD_LOG_FILE_SAVE_DAYS
      return now.time
    }

  val dateBefore2: Date
    /**
     * 得到现在时间前的几天日期，用来得到需要删除的日志文件名
     */
    get() {
      val nowtime = Date()
      val now = Calendar.getInstance()
      now.time = nowtime
      now[Calendar.DATE] = now[Calendar.DATE] - 1
      return now.time
    }



}
